package com.itheima.service.Impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.AddressDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Address;
import com.itheima.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.List;


/**
 * 李骏
 */
@Service(interfaceClass = AddressService.class)
@Transactional
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressDao addressDao;
    @Autowired
    private JedisPool jedisPool;

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        String queryString = queryPageBean.getQueryString();
        Integer pageSize = queryPageBean.getPageSize();
        Integer currentPage = queryPageBean.getCurrentPage();
        PageHelper.startPage(currentPage, pageSize);
        Page<Address> addresses = addressDao.selectByCondition(queryString);
        long total = addresses.getTotal();
        List<Address> result = addresses.getResult();
        return new PageResult(total, result);
    }

    @Override
    public void add(Address address) {
        addressDao.add(address);
        String img = address.getImg();
        if (img != null) {
            Jedis resource = jedisPool.getResource();
            resource.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, img);
            resource.close();
        }
    }

    @Override
    public void deleteById(Integer id) {
        Address byId = this.findById(id);
        String img = byId.getImg();
//        addressDao.deleteAddressAndOrder(id);
        addressDao.deleteById(id);
        if (img != null) {
            Jedis resource = jedisPool.getResource();
            resource.srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES, img);
            resource.close();
        }

    }

    public Address findById(Integer id) {
        Address address = addressDao.findById(id);
        return address;
    }

    @Override
    public void edit(Address address) {
        addressDao.edit(address);
        Integer id = address.getId();
        Address address1 = findById(id);
        String img1 = address1.getImg();
        String img2 = address.getImg();
        if (img1 != null && img2 != null && !img1.equals(img2)) {
            Jedis resource = jedisPool.getResource();
            resource.srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES, img1);
            resource.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, img2);
            resource.close();
        }
    }

    @Override
    public List<Address> findAll() {
        return addressDao.findAll();
    }
}
